package com.tqfframe.rabbitmq.service;

import com.tqfframe.rabbitmq.constants.RabbitConstants;
import com.tqfframe.rabbitmq.entity.TestEntity;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author: Qifeng Tang
 * @date: 2022/11/17 10:43
 * @Version 1.0
 **/
@Service
public class DelayService {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    // 发送延时信息
    public void sendTimeoutMsg(String content, String routingKey, int delay) {
        // 通过广播模式发布延时消息，会广播至每个绑定此交换机的队列，这里的路由键没有实质性作用
        rabbitTemplate.convertAndSend(RabbitConstants.DELAY_EXCHANGE, routingKey, content, message -> {
            message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
            // 毫秒为单位，指定此消息的延时时长
            message.getMessageProperties().setDelay(delay * 1000);
            return message;
        });
    }


    // 发送延时信息
    public void sendTimeoutMsg2(String content, String routingKey, int delay) {
                TestEntity testEntity=new TestEntity(content,"222");
//        String testEntity=content;
        //给消息设置过期时间
        MessagePostProcessor messagePostProcessor = message -> {
            message.getMessageProperties().setContentEncoding("UTF-8");
            message.getMessageProperties().setTimestamp(new Date());
            message.getMessageProperties().setType("x-delayed-message");
            //消息延迟时间
            message.getMessageProperties().setDelay(delay * 1000);
            // x-delay 这个版本请求头获取不到, 自定义了一个delay-times 来获取延迟时间
            message.getMessageProperties().setHeader("delay-times",delay * 1000);
            return message;
        };
        rabbitTemplate.convertAndSend(RabbitConstants.DELAY_EXCHANGE,routingKey, testEntity,messagePostProcessor);
    }
}
